import requests
from bs4 import BeautifulSoup
def gethtml(url):
    try:
        re=requests.get(url,timeout=10)
        re.raise_for_status()
        re.encoding="utf-8"
        print("获取成功")
        return re.text
    except:
        print("获取失败")
        return ""

def gethtmldata(html):
    soup=BeautifulSoup(html,"html.parser")
    tb=soup.find_all("table",{"class":"rankingtable"})
    all_ls=[]
    for trs in tb[0].find_all("tr"):
        ls=[]
        for td in trs:
            if td.string!="\n":
                ls.append(td.string)
        all_ls.append(ls)
    all_ls[0][1]="公司名称"
    all_ls[0][2]="利润"
    return all_ls
def writedata(ls):
    with open(r"财富2.csv","w") as f:
        for line in ls:
            f.write(",".join(line[0:4])+"\n")
def main():
    url="http://www.fortunechina.com/fortune500/c/2019-07/22/content_339539.htm"
    html=gethtml(url)
    # gethtmldata(html)
    writedata(gethtmldata(html))

if __name__ == '__main__':
    main()